$(function(){
	var mDom = {
		$content : $("#product-content"),
		
		
		$search : $(".search"),
		$superiorIdInput : $("#superiorIdInput"),
		$userIdInput : $(".userIdInput"),
		$userNicknameInput : $(".userNicknameInput"),
		$userRoleSelect : $(".userRoleSelect"),
		$userAuthenticationStatusSelect : $(".userAuthenticationStatusSelect"),
		$startTime : $("#startTime"),
		$endTime : $("#endTime"),
		$size : $("#sizeVal"),

		$pageSelect : $(".pageSelect"),
		
		//操作
		$userContent : $(".user-content"),
		$operationTd : $(".operationTd"),
		
		$adjustUserModel : $("#adjustUser"),
		$modalTitle : $("#adjustUser .modal-title"),
		$searchUserTip : $(".searchUserTip"),
		$sureBtn : $("#adjustUser .sureBtn"),
    };
	
	var method = {
	    loading: function() {      // 显示加载按
	        $('.loading').show();
	    },
	    hideLoading: function() {    // 隐藏加载按钮
	        $('.loading').hide();
	    }
	}
	
	//--------------------------------------查询商品----------------------------------------------------
	mDom.$search.click(function(){
		var data = new Object();
//		data.superiorId = mDom.$superiorIdInput.val();
		data.userId = mDom.$userIdInput.val();
		data.userNickname = mDom.$userNicknameInput.val();
		data.userRole = mDom.$userRoleSelect.val();
		data.userAuthenticationStatus = mDom.$userAuthenticationStatusSelect.val();
		data.fromTime = mDom.$startTime.val();
		data.toTime = mDom.$endTime.val();
		data.size = mDom.$size.val();
		
		console.log("data:"+JSON.stringify(data));
		var url = base_url + '/admin/userAdmin/listUserAdmin.html';
		post(url, data);
	});
	//--------------------------------------查询商品----------------------------------------------------
	
	
	
	
	//--------------------------------------跳转页面----------------------------------------------------
	mDom.$pageSelect.change(function(){
		var $this = $(this);
		var page = $this.val();
		
		var url = $("#url").val();
		url = url + "&pageNum="+page;
		
		var data = new Object();
		console.log("url="+url);
		post(url, data);
	})
	//--------------------------------------跳转页面----------------------------------------------------
	
	
	
	
	//------------------------------------------------操作----------------------------------------------
	//改变审核状态
	var changeUserAuthenticationStatusTd = function(userAuthenticationStatusTd, user){
		userAuthenticationStatusTd.text(user.authenticationStatusStr);
	}
	
	//改变操作栏
	var changeOperationTd = function(operationTd, user){
		operationTd.html("");
		var html = "";
		if(user.authenticationStatus === 1){//审核中
			html = '<button class="btn btn-success passCheckBtn">审核成功</button> '
					  +'<button class="btn btn-danger failCheckBtn">审核失败</button> ';
			if(user.userRole === 2){//总代理
				html += '<button class="btn btn-success adjustGeneralAgentBtn">调整</button> ';
			}else if(user.userRole === 3){//会员
				html += '<button class="btn btn-success adjustMemberBtn">调整</button> ';
			}
		}else if(user.authenticationStatus === 2){//审核失败
			html = '<button class="btn btn-success passCheckBtn">审核成功</button> ';
			if(user.userRole === 2){//总代理
				html += '<button class="btn btn-success adjustGeneralAgentBtn">调整</button> ';
			}else if(user.userRole === 3){//会员
				html += '<button class="btn btn-success adjustMemberBtn">调整</button> ';
			}
		}else if(user.authenticationStatus === 3){//审核成功
			if(user.userRole === 2){//总代理
				html = '<button class="btn btn-warning setToPartnerBtn" data-toggle="modal" data-target="#setCorporate">设为合伙人</button> '
						  +'<button class="btn btn-success adjustGeneralAgentBtn">调整</button> ';
			}else if(user.userRole === 3){//会员
				html = '<button class="btn btn-warning setToPartnerBtn" data-toggle="modal" data-target="#setCorporate">设为合伙人</button> '
						  +'<button class="btn btn-danger setToGeneralAgentBtn">设为总代理</button> '
						  +'<button class="btn btn-success adjustMemberBtn">调整</button> ';
			}
			html = html + '<button class="btn btn-danger failCheckBtn">审核失败</button> ';
		}
		operationTd.html(html);
	}
	
	var changeUserInfo = function(userInfoTd, superiorInfoTd, user, superior){
		if(user!=null){
			var userText = user.userRoleStr+"/"+user.userId+"/"+user.userNickname;
			userInfoTd.text(userText);
		}
		if(superior==null){
			superiorInfoTd.text("-");
		}else{
			var superiorText = superiorText.userRoleStr+"/"+superiorText.userId+"/"+superiorText.userNickname;
			superiorInfoTd.text(superiorText);
		}
	}
	
	//刷新本页
	var refresh = function(){
		var url = $("#url").val();
		var pageNum = $("#pageValue").val();
		url = url + "&pageNum="+pageNum;
		window.location.href=url;
	}
	
	//审核成功
	mDom.$userContent.on('click', '.passCheckBtn', function(){
		var $this = $(this);
		// 成功回调
		var success = function(data) {
			alert(data.retMsg);
			if(data.code === 1){
				var user = data.data;
				var userAuthenticationStatusTd = $this.parents('tr').find('.userAuthenticationStatusTd');
				changeUserAuthenticationStatusTd(userAuthenticationStatusTd, user);
				
				var operationTd = $this.parents('tr').find('.operationTd');
				changeOperationTd(operationTd, user);
			}else{
				
			}
		}

		var error = function() {
			alert("加载失败")
		}

		var userId = $this.parents('tr').attr('data-userId');
		var data = new Object();
		data.userId = userId;
		var params = "jsonSearchCondition=" + JSON.stringify(data);
		var url = base_url + "/admin/userAdmin/passCheck.do";
		console.log("url="+url+"----params="+params);
		// 进行请求
		doAjax("POST", url, params, success, error, true, false);
	})
	
	
	
	
	//审核失败
	mDom.$userContent.on('click', '.failCheckBtn', function(){
		var $this = $(this);
		// 成功回调
		var success = function(data) {
			alert(data.retMsg);
			if(data.code === 1){
				var user = data.data;
				var userAuthenticationStatusTd = $this.parents('tr').find('.userAuthenticationStatusTd');
				changeUserAuthenticationStatusTd(userAuthenticationStatusTd, user);
				
				var operationTd = $this.parents('tr').find('.operationTd');
				changeOperationTd(operationTd, user);
			}else{
				
			}
		}

		var error = function() {
			alert("加载失败")
		}

		var userId = $this.parents('tr').attr('data-userId');
		var data = new Object();
		data.userId = userId;
		var params = "jsonSearchCondition=" + JSON.stringify(data);
		var url = base_url + "/admin/userAdmin/failCheck.do";
		console.log("url="+url+"----params="+params);
		// 进行请求
		doAjax("POST", url, params, success, error, true, false);
	});
	
	
	//初始化调整用户模拟框
	var adjustUserId = null;
	var adjustFlag = 0;
	var userIsCheck = false;
	var initModel = function(title){
		$('#newSuperiorId').val("");
    	$('#checkResult').html("");
    	mDom.$modalTitle.text(title);
    	mDom.$adjustUserModel.modal('show');
    	$('.adjustUserBtn').attr({"disabled":false});
    	method.hideLoading();
    	userIsCheck = false;
	}
	
	
	//查询需要调整的用户下
	$('#searchUserBtn').on('click',function(){
		userIsCheck = false;
		var newSuperiorId = $('#newSuperiorId').val();
    	method.loading();
    	var searchUserByUserId = base_url + "/admin/userAdmin/searchUserByUserId.do";
        $.ajax({
            type: 'GET',
            data: 'userId=' + newSuperiorId,
            url: searchUserByUserId,
            success: function(result){
                if(result.code == 1){
                	userIsCheck = true;
                	var user = result.data;
                    $('#checkResult').html('<tr>'+
                    		'<td>'+user.userId+'</td>'+
                    		'<td><img src="'+user.userHeadPortrait+'"></td>'+
                            '<td>'+user.userNickname+'</td>'+
                            '<td>'+user.userRoleStr+'</td>'+
                            '<input type="hidden" value="'+user.userRole+'" class="newSuperiorRole">'+
                            '</tr>')
                    method.hideLoading();
                }else if(result.code == 0){
                	alert(result.retMsg);
                	method.hideLoading();
                }
            }
        })
    });
	
	//----------------------------------------------调整总代理----------------------------------------------
	mDom.$userContent.on('click', '.adjustGeneralAgentBtn', function(){
		var $this = $(this);
		adjustUserId = $this.parents('tr').attr('data-userId');
		initModel("调整总代理");
		mDom.$searchUserTip.text("总代理只能调整到合伙人下！");
		mDom.$searchUserTip.show();
		adjustFlag = 1;
	});
	//----------------------------------------------调整总代理----------------------------------------------
	
	
	
	//----------------------------------------------调整会员----------------------------------------------
	mDom.$userContent.on('click', '.adjustMemberBtn', function(){
		var $this = $(this);
		adjustUserId = $this.parents('tr').attr('data-userId');
		initModel("调整会员");
		mDom.$searchUserTip.hide();
		adjustFlag = 2;
	});
	//----------------------------------------------调整会员----------------------------------------------
	
	
	
	//----------------------------------------------会员升级为总代----------------------------------------------
	mDom.$userContent.on('click', '.setToGeneralAgentBtn', function(){
		var $this = $(this);
		adjustUserId = $this.parents('tr').attr('data-userId');
		initModel("调整会员设为总代");
		mDom.$searchUserTip.text("总代理只能调整到合伙人下！");
		mDom.$searchUserTip.show();
		adjustFlag = 3;
	});
	//----------------------------------------------会员升级为总代----------------------------------------------
	
	
	
	
	//确认调整用户
	mDom.$sureBtn.on('click',function(){
		if(userIsCheck === true){
			//调整后的上级id
	        var newSuperiorId = $('#newSuperiorId').val();
	        //
	        var newSuperiorRole = $(".newSuperiorRole").val();
	        if(newSuperiorId === ""){
	        	alert("请先输入调整到的用户id");
	        }else{
	        	if(newSuperiorId == adjustUserId){
	            	alert("不能把上级设置为自己！");
	            }else{
	            	var success = function(data) {
	        			alert(data.retMsg);
	        			if(data.code === 1){
        				 	$('.adjustUserBtn').attr({"disabled":false});
        	                $('#adjustUser').modal('hide');
        	                method.hideLoading();
        	                
        	                refresh();
	        			}else{
	        				console.log("数据搜索失败");
	        			}
	        		}

	        		var error = function() {
	        			alert("加载失败")
	        		}

	        		var doAjaxFlag = true;
	        		var url = "";
	        		if(adjustFlag === 1){//调整总代理
	        			if(newSuperiorRole != "1"){
	        				alert("总代理只能调整到合伙人下！");
	        				doAjaxFlag = false;
	        			}else{
	        				url = base_url + '/admin/userAdmin/adjustGeneralAgent.do';
	        			}
	        		}else if(adjustFlag === 2){//调整会员
	        			url = base_url + '/admin/userAdmin/adjustMember.do';
	        		}else if(adjustFlag === 3){
	        			if(newSuperiorRole != "1"){
	        				alert("设为总代理只能调整到合伙人下！");
	        				doAjaxFlag = false;
	        			}else{
	        				url = base_url + '/admin/userAdmin/setMemberToGeneralAgent.do';
	        			}
	        		}else{
	        			doAjaxFlag = false;
	        			alert("操作错误：未知调整用户方式！");
	        		}
	        		if(doAjaxFlag === true){
	        			$(".adjustUserBtn").attr({"disabled":"disabled"});
	                	method.loading();
	        			
	        			var data = new Object();
	            		data.userId = adjustUserId;
	            		data.newSuperiorId = newSuperiorId;
	            		var params = "jsonSearchCondition=" + JSON.stringify(data);
	            		console.log("url="+url+"----params="+params);
	        			// 进行请求
	            		doAjax("POST", url, params, success, error, true, false);
	        		}
	            }
	        }
		}else{
			alert("请先查询出新的上级！");
		}
        
    });
	
	
	//----------------------------------------------会员、总代升级为合伙人----------------------------------------------
	mDom.$userContent.on('click', '.setToPartnerBtn',function(){
    	var $this = $(this);
    	$('.adjustUserBtn').attr({"disabled":false});
    	method.hideLoading();
    	adjustUserId = $this.parents('tr').attr('data-userId');
    });
	
	$('#setToPartnerSure').on('click',function(){
		method.loading();
    	$(".adjustUserBtn").attr({"disabled":"disabled"});
    	console.log("adjustUserId="+adjustUserId);
        
        var success = function(data) {
			alert(data.retMsg);
			if(data.code === 1) {
                $('.adjustUserBtn').attr({"disabled":false});
                $('#setCorporate').modal('hide');
                method.hideLoading();
                
                refresh();
            }else if(data.code==3){
            	alert("请重新登录！");
	    		console.log("数据搜索失败");
	    	}else{
                console.error("请求异常");
            }
		}

		var error = function() {
			alert("加载失败")
		}
        
        var url = base_url + '/admin/userAdmin/setToPartner.do';
        var data = new Object();
		data.userId = adjustUserId;
		var params = "jsonSearchCondition=" + JSON.stringify(data);
		console.log("url="+url+"----params="+params);
		// 进行请求
		doAjax("POST", url, params, success, error, true, false);
    });
    //----------------------------------------------会员、总代升级为合伙人----------------------------------------------
	
	//------------------------------------------------操作----------------------------------------------
	
});